package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.admin.AdminConstants;
import com.heima.common.exception.CustException;
import com.heima.feigns.article.ArticleFeign;
import com.heima.feigns.wemedia.WemediaFeign;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.ApUserDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.pojos.ApUserRealname;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.mapper.ApUserRealnameMapper;
import com.heima.user.service.ApUserRealnameService;
import io.seata.spring.annotation.GlobalTransactional;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class ApUserRealnameServiceImpl extends ServiceImpl<ApUserRealnameMapper, ApUserRealname> implements ApUserRealnameService {
    /**
     * 条件分页查询
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findPage(ApUserDto dto) {
        //参数校验
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        dto.checkParam();

        //查询条件判断
        LambdaQueryWrapper<ApUserRealname> wrapper = Wrappers.<ApUserRealname>lambdaQuery();
        if (dto.getStatus() != null) {
            wrapper.eq(ApUserRealname::getStatus, dto.getStatus());
        }
        Page<ApUserRealname> pages = new Page<>(dto.getPage(), dto.getSize());

        //执行查询
        IPage<ApUserRealname> page = page(pages, wrapper);

        //结果封装返回
        return new PageResponseResult(dto.getPage(), dto.getSize(), page.getTotal(), page.getRecords());
    }

    @Autowired
    ApUserMapper apUserMapper;

    /**
     * 自媒体用户审核(通过/不通过)
     *
     * @param dto
     * @param status
     * @return
     */
    @GlobalTransactional(rollbackFor = Exception.class)
    @Override
    public ResponseResult updateStatusById(ApUserDto dto, Short status) {
        //参数校验
        if (dto == null || dto.getId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //根据id和待审核状态查询userRealname
        ApUserRealname apUserRealname = getOne(Wrappers.<ApUserRealname>lambdaQuery()
                .eq(ApUserRealname::getId, dto.getId())
                .eq(ApUserRealname::getStatus, 1));
        if (apUserRealname == null || apUserRealname.getUserId() == null) {
            //不存在抛异常
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //判断来认证的用户是否是普通用户
        ApUser apUser = apUserMapper.selectOne(Wrappers.<ApUser>lambdaQuery()
                .eq(ApUser::getId, apUserRealname.getUserId())
                .eq(ApUser::getStatus, 0));
        if (apUser == null) {
            //不存在抛异常
            CustException.cust("当前AP用户非法");
        }
        //存在则可以修改userRealname
        apUserRealname.setStatus(status);
        apUserRealname.setUpdatedTime(new Date());
        if (StringUtils.isNotBlank(dto.getMsg())) {
            apUserRealname.setReason(dto.getMsg());
        }
        updateById(apUserRealname);

        //根据状态码判断是否审核通过
        if (AdminConstants.PASS_AUTH.equals(status)) {
            //通过则增加自媒体用户
            WmUser wmUser = creatWmUser(apUser);
            if (wmUser == null) {
                CustException.cust("保存自媒体用户失败");
            }
            //通过则增加文章作者
            boolean flag = createApAuthor(wmUser);
            if (!flag) {
                CustException.cust("保存文章作者失败");
            }
            //通过则修改用户flag
            apUser.setFlag((short) 1);
            apUserMapper.updateById(apUser);
        }
//        int i = 1 / 0;
        return ResponseResult.okResult();
    }

    @Autowired
    WemediaFeign wemediaFeign;

    /**
     * 增加自媒体用户
     *
     * @param apUser
     * @return
     */
    private WmUser creatWmUser(ApUser apUser) {
        //先查询
        WmUser wmUser = wemediaFeign.findByName(apUser.getName());
        //不存在则新增
        if (wmUser == null) {
            wmUser = new WmUser();
            BeanUtils.copyProperties(apUser, wmUser);
            wmUser.setNickname(apUser.getName());
            wmUser.setApUserId(apUser.getId());
            wmUser.setCreatedTime(new Date());
            wmUser.setStatus(9);
            WmUser save = wemediaFeign.save(wmUser);
            if (save != null && save.getId() != null) {
                return save;
            }
        }
        return null;
    }

    @Autowired
    ArticleFeign articleFeign;

    /**
     * 增加文章作者
     *
     * @param wmUser
     * @return
     */
    private boolean createApAuthor(WmUser wmUser) {
        //查询
        ApAuthor apAuthor = articleFeign.findByUserId(wmUser.getApUserId());
        //不存在则新增
        if (apAuthor == null) {
            apAuthor = new ApAuthor();
            apAuthor.setName(wmUser.getName());
            apAuthor.setCreatedTime(new Date());
            apAuthor.setType(2);
            apAuthor.setUserId(wmUser.getApUserId());
            apAuthor.setWmUserId(wmUser.getId());
            boolean save = articleFeign.save(apAuthor);
            return save;
        }
        return false;
    }
}
